package com.alstudio.ui.base;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;

import org.json.JSONException;
import org.json.JSONObject;

import wxapi.WeiXin;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.app.VersionConfig;
import com.alstudio.core.app.ALUpdateApkManager;
import com.alstudio.core.mission.ALMissionManager;
import com.alstudio.core.voip.ALVoipCallUIEventCallback;
import com.alstudio.core.voip.ALVoipUIEvent;
import com.alstudio.event.ALEventDeliver;
import com.alstudio.module.ALModuleManager;
import com.alstudio.module.sns.base.SnsConfig;
import com.alstudio.module.sns.sina.SinaWeibo;
import com.alstudio.module.sns.tencent.ITencent;
import com.alstudio.module.sns.tencent.ITencent.OnAuthEventListener;
import com.alstudio.module.sns.weiboshare.IWeiboShare;
import com.alstudio.module.sns.weiboshare.IWeiboShare.Callback;
import com.alstudio.module.sns.weiboshare.ShareContentParam;
import com.alstudio.module.sns.weiboshare.ThirdPartFactory;
import com.alstudio.module.sns.weiboshare.WeiXinShare;
import com.alstudio.module.sns.weiboshare.WeiboShareFactory;
import com.alstudio.module.sns.weiboshare.WeiboShareUtil;
import com.alstudio.module.sns.weiboshare.WeiboShareUtil.WeiboShareMenuItem;
import com.alstudio.module.voip.ALPostToRtpServerData;
import com.alstudio.module.voip.ALVoipEvent;
import com.alstudio.module.voip.ALVoipEventType;
import com.alstudio.module.voip.ALVoipModuleManager;
import com.alstudio.module.xmpp.ALXmppEventCallback;
import com.alstudio.module.xmpp.protocol.xmpp.XmppErrorCode;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALXmppConnectionState;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALXmppData;
import com.alstudio.module.xmpp.protocol.xmpp.packact.ALMessage;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.module.xmpp.request.ALUiXmppRequestEvent;
import com.alstudio.module.xmpp.request.ALUiXmppRequestType;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.pojo.module.server.ServerInfo;
import com.alstudio.pojo.module.user.User;
import com.alstudio.ui.module.economy.UserWalletActivity;
import com.alstudio.ui.module.main.MainActivity;
import com.alstudio.utils.activity.ALActivityManager;
import com.alstudio.utils.activity.ALActivityManager.ActivityLifeCycleState;
import com.alstudio.utils.android.net.ALConnectionManager;
import com.alstudio.utils.android.net.ALConnectionManager.ALConnectionType;
import com.alstudio.utils.android.net.ALNetworkChangedListener;
import com.alstudio.utils.log.ALLog;
import com.alstudio.utils.umeng.UmengUtils;
import com.alstudio.view.animation.AnimationEndListener;
import com.alstudio.view.dialog.AlertDialogCreator;
import com.alstudio.view.listener.AlDialogOnClickListener;
import com.alstudio.view.listener.AlItemOnClickListener;
import com.alstudio.view.listener.ViewEventListener;
import com.alstudio.view.toast.MyToastUtil;
import com.loovee.imaohu.R;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.openapi.legacy.UsersAPI;

/**
 * 所有UI的基类
 * 
 * @author alonso lee
 * 
 */
public abstract class BaseActivity extends FragmentActivity implements
		ALNetworkChangedListener, OnClickListener, ALXmppEventCallback,
		ALVoipCallUIEventCallback {

	/* 界面名称 */
	public String activityName;
	/* 此变量用于描述是否需要接收ALXmppEventNotifier的回调通知 */
	private boolean callbackEnable = false;

	public Handler mhandler;

	private ActivityLifeCycleState mActivityState;

	// 通知区域事件监听器
	private NoticeAreaEventListener mNoticeAreaListener;
	// 此变量用于标识当前是否正在显示通知区域
	private boolean isNoticeAreaShowing = false;
	// 此变量用于标识是否需要定时自动关闭通知区域
	private boolean isAutoDismissNoticeAreaEnable = true;
	// 通知区域缺省显示时常
	private long NOTICE_AREA_SHOW_DURATION = 5 * 1000;
	// 通知区域显示时常
	private long mNoticeAreaShowDuration = NOTICE_AREA_SHOW_DURATION;
	// 自定义通知区域显示动画资源
	private int mNoticeAreaShowAnimationRes = -1;
	// 自定义通知区域隐藏动画资源
	private int mNoticeAreaDismissAnimationRes = -1;
	// 关闭通知区域
	private final int DISMISS_NOTICE_AREA = 10010;
	// 此变量标识界面当前是否可见
	private boolean isActivityOn = false;

	// 内容布局
	private LinearLayout contentLayout;
	// 通知区域
	private LinearLayout noticeLayout;
	// 通知区域的显示、隐藏动画
	private Animation noticeAnimation;

	// 標示是否已經等到數據
	protected boolean isDataReceived = false;

	protected boolean isUIinited = false;

	protected final String SHARE_USE_TASK_ID = "50108";
	public final String SHARE_RECEIVE_GIFT_TASK_ID = "50203";
	protected final String SHARE_MAGIC_TASK_ID = "50304";
	protected final String SHARE_HOME_PAGE = "50402";

	private void notifyActivityLifeCycleStateChanged(
			ActivityLifeCycleState state, BaseActivity a) {
		ALLog.d("activity life cycle changed!last state is " + mActivityState
				+ " current state is " + state);
		mActivityState = state;
		ALActivityManager.getALActivityManager().notifyLifeCycleStateChanged(
				state, a);
	}

	public ActivityLifeCycleState getActivityState() {
		return mActivityState;
	}

	public boolean isActivityOn() {
		return this.isActivityOn;
	}

	public void backToSystemHome() {
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// 设定基本布局
		setContentView(R.layout.base_layout);
		// 初始化变量
		initEnv();
		// // 初始化页面数据
		// initData();
		ALConnectionManager.AddNetworkChangedListener(this);
		ALEventDeliver.getDefaultAlEventDeliver().register(this);
		notifyActivityLifeCycleStateChanged(ActivityLifeCycleState.CREATE, this);
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		invokeClearActivityEnv();
		dismissLoadingProgress();
		// 移除网络状态监听
		ALConnectionManager.removeNetworkChangedListener(this);
		// 移除事件监听
		ALEventDeliver.getDefaultAlEventDeliver().unregister(this);
		ALLocalEnv.mXmppEventNotifyManager.unRegisterListener(this);
		// overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
		notifyActivityLifeCycleStateChanged(ActivityLifeCycleState.FINISH, this);
		ALLog.d("界面 " + activityName + "已经关闭");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		notifyActivityLifeCycleStateChanged(ActivityLifeCycleState.DESTROY,
				this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isActivityOn = true;
		checkNewVersionAlert();
		notifyActivityLifeCycleStateChanged(ActivityLifeCycleState.RESUME, this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		isActivityOn = false;
		notifyActivityLifeCycleStateChanged(ActivityLifeCycleState.PAUSE, this);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		notifyActivityLifeCycleStateChanged(ActivityLifeCycleState.STOP, this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		notifyActivityLifeCycleStateChanged(ActivityLifeCycleState.START, this);
	}

	@Override
	public void onBackPressed() {
		finish();
	}

	/**
	 * 初始化变量
	 * 
	 * @author alonso lee
	 */
	private void initEnv() {
		// 获取界面内容区
		contentLayout = (LinearLayout) findViewById(R.id.content_layout);
		// 获取通知区域
		noticeLayout = (LinearLayout) findViewById(R.id.notice_area);
		mhandler = new Handler();
		// 强制只能竖屏
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

	}

	/**
	 * 请求获取数据
	 */
	public void requeqtData() {
		showLoadingProgress();
	}

	/**
	 * 此方法用于初始化UI
	 * 
	 * @author alonso lee
	 */
	protected void setupView(Context context, String name) {
		activityName = name;
		ALLocalEnv.mXmppEventNotifyManager.registerListener(this);
	}

	/**
	 * 设置内容区的布局文件
	 */
	public void setContentRes(int layoutResId) {
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(layoutResId, null);
		if (v != null) {
			v.setLayoutParams(new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			contentLayout.addView(v);
		}
	}

	/**
	 * 此方法用于设定各个view的点击事件监听器
	 * 
	 * @author alonso lee
	 */
	protected void setViewClickListener() {

	}

	/**
	 * 初始化页面数据
	 * 
	 * @author alonso lee
	 */
	abstract protected void initData();

	/**
	 * 设定页面进入全屏模式
	 * 
	 * @author alonso lee
	 */
	protected void enterFullScreenMode() {

		WindowManager.LayoutParams params = getWindow().getAttributes();
		params.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setAttributes(params);
		getWindow()
				.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
	}

	/**
	 * 设定页面退出全屏模式
	 * 
	 * @author alonso lee
	 */
	protected void exitFullScreenMode() {
		WindowManager.LayoutParams params = getWindow().getAttributes();
		params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
		getWindow().setAttributes(params);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
	}

	/**
	 * 显示加载进度条
	 */
	public void showLoadingProgress() {

	}

	/**
	 * 隐藏加载进度条
	 */
	public void dismissLoadingProgress() {

	}

	/**
	 * 设置加载进度条是否可以取消显示
	 * 
	 * @param cancelAble
	 */
	public void setLoadingProgressCancelAble(boolean cancelAble) {

	}

	/**
	 * 设定通知区域view事件监听器
	 * 
	 * @param listener
	 * @author Alonso Lee
	 */
	protected void setNoticeAreaListener(NoticeAreaEventListener listener) {
		if (listener != null) {
			mNoticeAreaListener = listener;
		}
	}

	/**
	 * 移除通知区域view事件监听器
	 * 
	 * @author Alonso Lee
	 */
	protected void removeNoticeAreaListener() {
		mNoticeAreaListener = null;
	}

	/**
	 * 将制定的view添加到通知区域中。
	 * 
	 * @param child
	 * @author Alonso Lee
	 */
	protected void setNoticeLayout(View child) {

		if ((noticeLayout != null) && (child != null)) {
			child.setLayoutParams(new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			noticeLayout.removeAllViews();
			noticeLayout.addView(child);
		}
	}

	/**
	 * 设定通知区域显示时常。传入的值为毫秒。
	 * 
	 * @param time
	 * @author Alonso Lee
	 */
	protected void setNoticeAreaShowDuration(long time) {
		if (time > 0) {
			mNoticeAreaShowDuration = time;
		}
	}

	/**
	 * 设定通知区域显示时的过场动画
	 * 
	 * @param res
	 *            -1则表示恢复缺省动画
	 * @author Alonso Lee
	 */
	protected void setNoticeAreaShowAnimationRes(int res) {
		mNoticeAreaShowAnimationRes = res;
	}

	/**
	 * 设定通知区域隐藏时的过场动画
	 * 
	 * @param res
	 *            -1则表示恢复缺省动画
	 * @author Alonso Lee
	 */
	protected void setNoticeAreaDismissAnimationRes(int res) {
		mNoticeAreaDismissAnimationRes = res;
	}

	/**
	 * 设定通知区域是否定时自动消失
	 * 
	 * @param enable
	 *            true表示需要自动消失 false 表示不需要自动消失
	 * @author Alonso Lee
	 */
	protected void setNoticeAreaAutoDismiss(boolean dismiss) {
		isAutoDismissNoticeAreaEnable = dismiss;
	}

	/**
	 * 检查通知区域当前是否设为定时自动消失
	 * 
	 * @return true 表示当前设定为自动消失
	 * @author Alonso Lee
	 */
	protected boolean isNoticeAreaAutoDismiss() {
		return isAutoDismissNoticeAreaEnable;
	}

	public void enterBlur() {
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.alpha = 0.8f;
		getWindow().setAttributes(lp);
		// onActivityEnterBlur();
	}

	public void exitBlur() {
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.alpha = 1.0f;
		getWindow().setAttributes(lp);
		// onActivityExitBlur();
	}

	public void enterDim() {
		WindowManager.LayoutParams windowManager = getWindow().getAttributes();
		windowManager.dimAmount = 0.25f;
		getWindow().setAttributes(windowManager);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
	}

	public void extiDim() {
		WindowManager.LayoutParams windowManager = getWindow().getAttributes();
		windowManager.dimAmount = 0.75f;
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
	}

	/**
	 * 显示通知区域
	 * 
	 * @author Alonso Lee
	 */
	protected void showBaseNotice() {
		if (noticeLayout != null) {
			dismissNotice(false, false);
			noticeLayout.setVisibility(View.VISIBLE);
			isNoticeAreaShowing = true;

			if (isAutoDismissNoticeAreaEnable) {
				noticeAreaHandler.sendEmptyMessageDelayed(DISMISS_NOTICE_AREA,
						mNoticeAreaShowDuration);
			}
			if (mNoticeAreaShowAnimationRes != -1) {
				// 设定自定义显示动画
				noticeAnimation = AnimationUtils.loadAnimation(this,
						mNoticeAreaShowAnimationRes);
			} else {
				// 使用缺省显示动画
				noticeAnimation = AnimationUtils.loadAnimation(this,
						R.anim.activity_down);
			}
			noticeAnimation.setAnimationListener(noticeAreaAnimationListener);
			noticeLayout.startAnimation(noticeAnimation);
		}
	}

	/**
	 * 隐藏通知区域
	 * 
	 * @author Alonso Lee
	 */
	protected void dismissNotice(boolean anim, boolean sendCallback) {

		if (noticeLayout != null) {
			noticeAreaHandler.removeMessages(DISMISS_NOTICE_AREA);

			isNoticeAreaShowing = false;

			if (anim) {
				if (mNoticeAreaDismissAnimationRes != -1) {
					// 设定自定义消失动画
					noticeAnimation = AnimationUtils.loadAnimation(this,
							mNoticeAreaDismissAnimationRes);
				} else {
					// 使用缺省显示动画
					noticeAnimation = AnimationUtils.loadAnimation(this,
							R.anim.activity_up);
				}
				noticeAnimation
						.setAnimationListener(noticeAreaAnimationListener);
				noticeLayout.startAnimation(noticeAnimation);
			} else {
				noticeLayout.setVisibility(View.GONE);

				if (sendCallback) {
					sendNoticeLayoutDismissCallback();
				}
			}
		}
	}

	private void sendNoticeLayoutDismissCallback() {
		// 回调通知，已经隐藏了
		if (mNoticeAreaListener != null) {
			mNoticeAreaListener.onDismiss();
		}

	}

	/**
	 * 此handler用于控制定时关闭通知区域
	 */
	private Handler noticeAreaHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			dismissNotice(true, true);
		};
	};

	/**
	 * 此类封装状态栏上的通知区域的回调接口
	 * 
	 * @author Alonso Lee
	 * 
	 */
	public interface NoticeAreaEventListener extends ViewEventListener {

	}

	private AnimationListener noticeAreaAnimationListener = new AnimationEndListener() {

		@Override
		public void onAnimationEnd(Animation animation) {
			if (isNoticeAreaShowing) {
				// 回调通知，已经正常显示了
				if (mNoticeAreaListener != null) {
					mNoticeAreaListener.onShow();
				}
				// 显示通知区域动画显示完毕，如果开启了定时自动关闭通知区域，那么延时通过handler实现
				if (isAutoDismissNoticeAreaEnable) {
					noticeAreaHandler.sendEmptyMessageDelayed(
							DISMISS_NOTICE_AREA, mNoticeAreaShowDuration);
				}

			} else {
				// 隐藏通知区域
				noticeLayout.setVisibility(View.GONE);
				// 回调通知，已经隐藏了
				sendNoticeLayoutDismissCallback();
			}
		}
	};

	/**
	 * 此方法用于测试当前界面是否需要接收xmpp事件回调
	 * 
	 * @return true 此界面需要接收xmpp事件回调; false 此界面不需要接收xmpp事件回调.
	 * @author alonso lee
	 */
	public boolean isCallbackEnable() {
		return this.callbackEnable;
	}

	/**
	 * 设定本界面需要接收xmpp事件回调
	 * 
	 * @author alonso lee
	 */
	protected void enableReceiveALXmppEvent() {
		// callbackEnable = true;
		ALEventDeliver.getDefaultAlEventDeliver().register(this);

	}

	/**
	 * 设定本界面不需要接收xmpp事件回调
	 * 
	 * @author alonso lee
	 */
	protected void disableReceiveALXmppEvent() {
		callbackEnable = false;
		ALEventDeliver.getDefaultAlEventDeliver().unregister(this);

	}

	/**
	 * 设置View点击事件监听器
	 * 
	 * @param viewId
	 *            view id
	 * @param listener
	 *            事件监听器
	 */
	protected void setViewOnclickListener(int viewId, OnClickListener listener) {
		if (findViewById(viewId) != null) {
			findViewById(viewId).setOnClickListener(listener);
		}
	}

	/**
	 * 设置View点击事件监听器
	 * 
	 * @param view
	 *            view实例对象
	 * @param listener
	 *            事件监听器
	 */
	protected void setViewOnclickListener(View view, OnClickListener listener) {
		if ((view) != null) {
			(view).setOnClickListener(listener);
		}
	}

	/**
	 * 设置TextView对象显示文字
	 * 
	 * @param res
	 *            TextView id
	 * @param msg
	 *            显示消息
	 */
	protected void showTextMessage(int res, String msg) {
		try {
			((TextView) findViewById(res)).setText(msg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 设置TextView对象显示文字
	 * 
	 * @param tv
	 *            TextView 对象实例
	 * @param msg
	 *            显示消息
	 */
	protected void showTextMessage(TextView tv, String msg) {
		if (tv != null) {
			tv.setText(msg);
		}
	}

	/**
	 * 设置TextView对象显示文字
	 * 
	 * @param res
	 *            TextView id
	 * @param msg
	 *            显示消息
	 */
	protected void showTextMessage(int res, int msg) {
		try {
			((TextView) findViewById(res)).setText(msg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 設置hint
	 * 
	 * @param res
	 * @param msg
	 */
	protected void setTextHint(int res, String msg) {
		try {
			((TextView) findViewById(res)).setHint(msg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 設置hint
	 * 
	 * @param res
	 * @param msg
	 */
	protected void SetTextHint(int res, int str) {
		try {
			((TextView) findViewById(res)).setHint(str);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 设置字体颜色
	 * 
	 * @param res
	 *            textview
	 * @param color
	 *            字体颜色
	 */
	protected void setTextColor(int res, int color) {
		try {
			((TextView) findViewById(res)).setTextColor(color);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 设置字体颜色
	 * 
	 * @param res
	 *            textview
	 * @param color
	 *            字体颜色
	 */
	protected void setTextColor(TextView textView, int color) {
		try {
			textView.setTextColor(color);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 显示View
	 * 
	 * @param res
	 *            View id
	 */
	protected void showView(int res) {
		try {
			findViewById(res).setVisibility(View.VISIBLE);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 显示View
	 * 
	 * @param view
	 *            待显示View实例对象
	 */
	protected void showView(View view) {
		try {
			view.setVisibility(View.VISIBLE);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 将指定View设为不可见
	 * 
	 * @param res
	 *            View id
	 */
	protected void invisibleView(int res) {
		try {
			findViewById(res).setVisibility(View.INVISIBLE);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 将指定View实例对象设为不可见
	 * 
	 * @param view
	 *            待设为不可见View实例对象
	 */
	protected void invisibleView(View view) {
		try {
			view.setVisibility(View.INVISIBLE);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 隐藏指定id的view
	 * 
	 * @param res
	 *            待隐藏view id
	 */
	protected void goneView(int res) {
		try {
			findViewById(res).setVisibility(View.GONE);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 隱藏View實例對象
	 * 
	 * @param view
	 *            待隐藏View对象
	 */
	protected void goneView(View view) {
		try {
			view.setVisibility(View.GONE);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 设置背景图
	 * 
	 * @param viewId
	 * @param bgRes
	 */
	protected void setViewBackground(int viewId, int bgRes) {
		try {
			findViewById(viewId).setBackgroundResource(bgRes);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 显示界面即将销毁对话框，点击确定按钮就关掉界面
	 * 
	 * @param content
	 */
	protected void showFinishActivityAlertDialog(String content) {
		AlertDialogCreator dialog = AlertDialogCreator
				.createOneButtonNormalDialog(this, false);
		dialog.setMessage(content);
		dialog.setCancelable(false);
		dialog.setCenterKeyListener(new AlDialogOnClickListener() {

			@Override
			public void onClick() {
				// TODO Auto-generated method stub
				finish();
			}
		});
		dialog.showDialog();
	}

	/**
	 * 显示一个单按钮的普通对话框，无点击事件
	 * 
	 * @param content
	 */
	protected void showInfoAlertDialog(String content) {
		AlertDialogCreator dialog = AlertDialogCreator
				.createOneButtonNormalDialog(this, false);
		dialog.setMessage(content);
		dialog.setCancelable(false);
		dialog.showDialog();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (mWeiboShare != null) {
			mWeiboShare.onActivityResult(requestCode, resultCode, data);
		}

		// 处理第三方登陆
		if (mSinaWeibo != null) {
			mSinaWeibo.authorizeCallBack(requestCode, resultCode, data);
		}

		if (mTencent != null) {
			mTencent.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	public int dip2px(Context context, float dipValue) {
		if (dipValue == 0) {
			return 0;
		}
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static final int LEFT = 1;
	public static final int RIGHT = 2;
	public static final int NONE = 3;

	// 设置图片
	protected void setCustomDrawable(int res, TextView view, int direction) {
		if (direction == NONE) {
			view.setCompoundDrawables(null, null, null, null); // 设置右图标
			return;
		}
		Drawable img = getResources().getDrawable(res);
		// 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
		img.setBounds(dip2px(this, 12), dip2px(this, 12), dip2px(this, 12),
				dip2px(this, 12));
		if (direction == LEFT) {
			view.setCompoundDrawables(img, null, null, null); // 设置左图标
		} else if (direction == RIGHT) {
			view.setCompoundDrawables(null, null, img, null); // 设置右图标
		}
	}

	/**
	 * 显示金币不足购买失败对话框
	 * 
	 * @author Alonso Lee
	 */
	public void showNoEnoughMoneyDialog() {
		AlertDialogCreator dialog = AlertDialogCreator
				.createTwoButtonNormalDialog(this, false);
		String message = getString(R.string.TxtNoEnoughGold);
		dialog.setMessage(message);
		dialog.setLeftButtonName(getString(R.string.TxtRechargeNow));
		dialog.setRightButtonName(getString(R.string.TxtRechargeLater));
		dialog.setLeftKeyListener(new AlDialogOnClickListener() {

			@Override
			public void onClick() {
				// TODO Auto-generated method stub
				Intent i = new Intent(BaseActivity.this,
						UserWalletActivity.class);
				startActivity(i);
			}
		});
		dialog.showDialog();
	}

	/**
	 * 清除界面对象资源
	 */
	public void invokeClearActivityEnv() {

	}

	/***************************************** 超时处理 *****************************************************************/
	// 超时时间设为20S 2013-3-1
	private final int REQUEST_DATA_TIME_OUT = 20 * 1000;
	// 超时事件
	private final int SHOW_REQUEST_DATA_TIME_OUT = 0;

	public interface TimeOutListener {
		public void onTimeout();
	}

	protected TimeOutListener mTimeoutListener;

	private Handler timeOutHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			// 回调通知超时了
			if (mTimeoutListener != null) {
				mTimeoutListener.onTimeout();
			}
			MyToastUtil.getInstance().showToastOnCenter(
					getString(R.string.TxtRequestTimeOut));
		}
	};

	protected void sendTimeoutEvent(TimeOutListener listener) {
		cancelTimeoutEvent();
		timeOutHandler.sendEmptyMessageDelayed(SHOW_REQUEST_DATA_TIME_OUT,
				REQUEST_DATA_TIME_OUT);
		mTimeoutListener = listener;
	}

	protected void sendTimeoutEvent(TimeOutListener listener, int timeout) {
		cancelTimeoutEvent();
		timeOutHandler.sendEmptyMessageDelayed(SHOW_REQUEST_DATA_TIME_OUT,
				timeout);
		mTimeoutListener = listener;
	}

	protected void cancelTimeoutEvent() {
		timeOutHandler.removeMessages(SHOW_REQUEST_DATA_TIME_OUT);
	}

	protected void showProgressBar(ProgressBar bar) {
		bar.setVisibility(View.VISIBLE);
	}

	protected void dismissProgressBar(ProgressBar bar) {
		bar.setVisibility(View.GONE);
		cancelTimeoutEvent();
	}

	/********************************************************* 打电话 *********************************************************************/

	public void makeCall() {
		String user = ALLocalEnv.getLocalEnv().getMyAccount().getUserName();
		ALPostToRtpServerData data = ALVoipModuleManager
				.getPostToRtpServerData(user, getIp(), 4000,
						ALConnectionManager.getConnectionTypeString(),
						ALVoipModuleManager.DEFAULT_RTP_SERVER_IP,
						ALVoipModuleManager.DEFAULT_RTP_SERVER_PORT);

		ALVoipEvent event = new ALVoipEvent();
		event.setData(data);
		event.setEventType(ALVoipEventType.ALVOIP_EVENT_POST_DATA_TO_RTP_SERVER);
		ALModuleManager.getDefaultModuleManager().postEventToModuleManager(
				event);
	}

	/**
	 * 提醒拨号失败
	 * 
	 * @param errorCode
	 */
	public void showMakeCallErrorToast(int errorCode) {
		// 缺省为未知错误
		int txt = R.string.TxtUnknowError;
		switch (errorCode) {
		case XmppErrorCode.XMPP_ERROR_801:
			txt = R.string.TxtMakeCallError801;
			break;
		case XmppErrorCode.XMPP_ERROR_802:
			txt = R.string.TxtMakeCallError802;
			break;
		case XmppErrorCode.XMPP_ERROR_803:
			txt = R.string.TxtMakeCallError803;

			break;
		case XmppErrorCode.XMPP_ERROR_804:
			txt = R.string.TxtMakeCallError804;

			break;
		case XmppErrorCode.XMPP_ERROR_805:
			txt = R.string.TxtMakeCallError805;

			break;

		default:
			break;
		}
		MyToastUtil.getInstance().showCenterToastOnCenter(txt);
	}

	public String getIp() {
		String localip = null;
		String netip = null;
		try {
			Enumeration<NetworkInterface> netInterfaces = NetworkInterface
					.getNetworkInterfaces();
			InetAddress ip = null;
			boolean finded = false;
			while (netInterfaces.hasMoreElements() && !finded) {
				NetworkInterface ni = netInterfaces.nextElement();
				Enumeration<InetAddress> address = ni.getInetAddresses();
				while (address.hasMoreElements()) {
					ip = address.nextElement();
					if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
							&& ip.getHostAddress().indexOf(":") == -1) {
						netip = ip.getHostAddress();
						finded = true;
						break;
					} else if (ip.isSiteLocalAddress()
							&& !ip.isLoopbackAddress()
							&& ip.getHostAddress().indexOf(":") == -1) {
						localip = ip.getHostAddress();
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		if (netip != null && !"".equals(netip)) {
			return netip;
		} else {
			return localip;
		}
	}

	/***************************************************** 第三方登陆 *****************************************************************/

	protected static String third_part_uid = "";
	protected static String third_part_token = "";
	protected static String third_part_token_secret = ""; // twitter需要
	protected static String third_part_nickname = "";
	protected static String third_part_gender = "";
	protected static Date third_part_birthday = null;
	protected static String third_part_avatar_path = "";

	// 缺省为系统账号登陆
	protected static int third_part_type = VersionConfig.LOGIN_TYPE_LOOVEE;

	// 发送第三方登录广播
	public void SendThirdPartLogin(int thirdPartType, String thirdPartUid) {
		ALLog.d("准备开始第三方登陆 " + thirdPartUid);

		Intent i = new Intent(/* Events.ACTION_REQUEST_THIRD_PART_LOGIN */);
		// i.putExtra("third_part_type", App.LOGIN_TYPE_FACEBOOK);
		i.putExtra("third_part_type", thirdPartType);
		i.putExtra("third_part_uid", thirdPartUid);
		sendBroadcast(i);
		ALXmppData data = ALLocalEnv.getLocalEnv().createALXmppData();
		data.setThirdPartType(thirdPartType);
		data.setThirdPartUid(thirdPartUid);
		ALUiXmppRequestEvent event = ALUiXmppRequestCreator
				.creatorALUiXmppEvent(
						ALUiXmppRequestType.XMPP_THIRD_PART_CHECK_REGISTER_STATE_REQUEST,
						data);

		ALModuleManager.getDefaultModuleManager().postEventToModuleManager(
				event);
	}

	/*---------------------------------------------------- 腾讯登陆  ------------------------------------------------------------------------*/
	// tencent应用实例
	private ITencent mTencent;

	/**
	 * 执行QQ登陆
	 */
	public void doTencentLogin() {
		mTencent = ThirdPartFactory.getTencentInstance(this);

		mTencent.setOnAuthEventListener(mTencentAuthListener);
		mTencent.login(this, SnsConfig.TENCENT_SCOPE, mTencentAuthListener);

	}

	private void getTencentUserInfo() {

		mTencent.getUserInfo(this, "get_simple_userinfo", false,
				getTencentInfoListener);
	}

	private OnAuthEventListener getTencentInfoListener = new ITencent.OnAuthEventListener() {

		@Override
		public void onCancel() {

		}

		@Override
		public void onAuthSuccess() {

		}

		@Override
		public void onAuthFailed(int ret, String msg) {

		}

		@Override
		public void doComplete(JSONObject response, Object state) {

			JSONObject jsonObj = response;

			try {
				third_part_nickname = jsonObj.getString("nickname");
				third_part_uid = mTencent.getOpenId();
				ALLog.d("QQ登陆，昵称 " + third_part_nickname + " uid "
						+ third_part_uid);
			} catch (JSONException e) {
				ALLog.d(e.getMessage());
				e.printStackTrace();
			}

			SendThirdPartLogin(VersionConfig.LOGIN_TYPE_TENCENT, third_part_uid);
		}
	};

	private ITencent.OnAuthEventListener mTencentAuthListener = new ITencent.OnAuthEventListener() {
		@Override
		public void onAuthSuccess() {
			// 获取QQ用户昵称和id
			getTencentUserInfo();
			// QQ授权验证成功
			third_part_type = VersionConfig.LOGIN_TYPE_TENCENT;

			ALLog.d(String.format("QQ授权验证成功, access token : %s",
					mTencent.getAccessToken()));
		}

		@Override
		public void onAuthFailed(final int error_ret, final String error_des) {
			// QQ授权验证失败
			ALLog.d(String.format("QQ授权验证失败, ret : %s, msg : %s", error_ret,
					error_des));

			SendThirdPartLogin(VersionConfig.LOGIN_TYPE_TENCENT, third_part_uid);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {

					MyToastUtil.getInstance().showToastOnCenter(
							getString(R.string.TxtSnsLoginAuthFail));
				}
			});
		}

		@Override
		public void onCancel() {

		}

		@Override
		public void doComplete(JSONObject response, Object state) {
		}
	};

	/*---------------------------------------------------- 腾讯登陆  ------------------------------------------------------------------------*/

	/*---------------------------------------------------- 新浪登陆  ------------------------------------------------------------------------*/
	// sina应用实例
	private SinaWeibo mSinaWeibo;

	public void doSinaLogin() {
		// mSinaWeibo = ThirdPartFactory.getSinaWeiboInstance();
		//
		// mSinaWeibo.authorize(this, true, mSinaAuthListener);
		ALLog.d("执行新浪SSO登陆");
		mSinaWeibo = ThirdPartFactory.getSinaWeiboInstance(this);
		mSinaWeibo.authorize(this, mSinaLoginAuthListener);
	}

	private com.sina.weibo.sdk.net.RequestListener listener = new com.sina.weibo.sdk.net.RequestListener() {

		@Override
		public void onIOException(IOException e) {

		}

		@Override
		public void onError(WeiboException e) {

		}

		@Override
		public void onComplete(String response) {

			mSinaWeibo.getUserInfoAsyn(
					new com.alstudio.module.sns.sina.SinaWeibo.Callback() {

						@Override
						public void onSuccess(Object obj) {
							com.alstudio.module.sns.sina.UserInfo user = (com.alstudio.module.sns.sina.UserInfo) obj;

							ALLog.d("third part nickname : "
									+ user.getScreenName());

							third_part_nickname = user.getScreenName();
							third_part_gender = user.getGender();
							third_part_type = VersionConfig.LOGIN_TYPE_SINA;

							ALLog.d("third part nickname : "
									+ third_part_nickname);
							ALLog.d("third part gender : " + third_part_gender);

							SendThirdPartLogin(VersionConfig.LOGIN_TYPE_SINA,
									third_part_uid);

						}

						@Override
						public void onError(int ret, String msg) {

							ALLog.d(String.format(
									"无法获取用户信息 (ret : %d, msg : %s)", ret, msg));

							third_part_uid = mSinaWeibo.getUid();

							SendThirdPartLogin(VersionConfig.LOGIN_TYPE_SINA,
									third_part_uid);
						}
					}, response);
		}

		@Override
		public void onComplete4binary(ByteArrayOutputStream arg0) {
			// TODO Auto-generated method stub

		}
	};

	private com.alstudio.module.sns.sina.SinaWeibo.OnAuthEventListener mSinaLoginAuthListener = new com.alstudio.module.sns.sina.SinaWeibo.OnAuthEventListener() {

		@Override
		public void onAuthSuccess() {

			// 新浪微博授权验证成功
			// login_type = VersionConfig.LOGIN_TYPE_SINA;

			third_part_token = mSinaWeibo.getAccessToken().getToken();
			ALLog.d(String.format("新浪微博授权验证成功, access token : %s", mSinaWeibo
					.getAccessToken().getToken()));

			third_part_uid = mSinaWeibo.getUid();

			ALLog.d("third part uid ==>: " + third_part_uid);
			long uid = 0;
			if (third_part_uid != null) {

				uid = Long.valueOf(third_part_uid); // 2937204437
			}
			UsersAPI usersAPI = new UsersAPI(mSinaWeibo.getAccessToken());
			usersAPI.show(uid, listener);

		}

		@Override
		public void onCancel() {
			ALLog.d("取消新浪微博授权");

		}

		@Override
		public void onAuthFailed(String msg) {
			ALLog.d(String.format("新浪微博授权失败, msg : %s", msg));

			runOnUiThread(new Runnable() {

				@Override
				public void run() {

					MyToastUtil.getInstance().showToastOnCenter(
							getString(R.string.TxtSnsLoginAuthFail));
				}
			});
		}

	};

	/*---------------------------------------------------- 新浪登陆  end------------------------------------------------------------------------*/

	/***************************************************** 第三方登陆 end *****************************************************************/

	/***************************************************************** 分享 ***************************************************************/
	private boolean isFollowDone, isShareDone; // 是否完成操作
	private boolean isFollowSuccess, isShareSuccess; // 是否操作成功
	private boolean isShowTip;

	private String mShareContent;
	private boolean mNeedGetGold = false; // 是否需要向服务器要金币
	private boolean mIsFollow = false; // 是否需要关注
	private int mWeiboType = 0;
	private String mMissionId = "10010"; // 任务id,null时表示不是分享任务
	protected IWeiboShare mWeiboShare;
	private boolean isDoingShare = false;

	public void shareDirect(final ArrayList<WeiboShareMenuItem> menuItem,
			final ShareContentParam param, final boolean isNeedGold,
			final boolean isFollow, final String missionId, final String url,
			final boolean isFinishRequest) {
		int count = menuItem.size();
		if (menuItem == null || count < 1)
			return;

		String[] items = new String[count + 1];
		for (int i = 0; i < count; ++i) {
			WeiboShareMenuItem item = menuItem.get(i);
			if (item == null)
				return;

			items[i] = menuItem.get(i).menuText;
		}

		items[count] = getString(R.string.BtnCancel);

		{
			AlertDialogCreator mDialogCreator = AlertDialogCreator
					.createNoButtonWithListItemDialog(this, false, items);
			// mDialogCreator
			// .setTitle(getString(R.string.string_weibo_share_dialog_title));
			mDialogCreator.setItemClickListener(new AlItemOnClickListener() {

				@Override
				public void OnClick(int which) {
					// TODO Auto-generated method stub

					if (which >= 0 && which < menuItem.size()) {
						final int shareTo = menuItem.get(which).shareTo;

						shareDirect(shareTo, param, isNeedGold, isFollow,
								missionId, url);
					}

					if (isFinishRequest) {
						finish();
					}

				}
			});
			mDialogCreator.showDialog();
		}
	}

	public void shareDirect(final ArrayList<WeiboShareMenuItem> menuItem,
			final ShareContentParam param, final boolean isNeedGold,
			final boolean isFollow, final String missionId, final String url) {
		int count = menuItem.size();
		if (menuItem == null || count < 1)
			return;

		String[] items = new String[count + 1];
		for (int i = 0; i < count; ++i) {
			WeiboShareMenuItem item = menuItem.get(i);
			if (item == null)
				return;

			items[i] = menuItem.get(i).menuText;
		}

		items[count] = getString(R.string.BtnCancel);
		{

			AlertDialogCreator mDialogCreator = AlertDialogCreator
					.createNoButtonWithListItemDialog(this, false, items);
			// mDialogCreator
			// .setTitle(getString(R.string.string_weibo_share_dialog_title));
			mDialogCreator.setItemClickListener(new AlItemOnClickListener() {

				@Override
				public void OnClick(int which) {
					// TODO Auto-generated method stub

					if (which >= 0 && which < menuItem.size()) {
						final int shareTo = menuItem.get(which).shareTo;

						shareDirect(shareTo, param, isNeedGold, isFollow,
								missionId, url);
					}

				}
			});
			mDialogCreator.showDialog();

		}
	}

	private int shareChannel = -1;

	private String shareChannelStr = "";

	public void shareDirect(final int shareTo, final ShareContentParam param,
			final boolean isNeedGold, final boolean isFollow,
			final String missionId, String url) {

		boolean isShareWeixin = false;
		if (!ALLocalEnv.isNetworkConnected())
			return;

		mIsFollow = isFollow;
		mNeedGetGold = isNeedGold;
		mMissionId = missionId;

		String wayValue = null;
		switch (shareTo) {
		case WeiboShareUtil.SHARE_TO_FACEBOOK:
			wayValue = UmengUtils.WeiboTypeValue.FACEBOOK;
			mWeiboShare = WeiboShareFactory
					.getInstance(WeiboShareFactory.FACEBOOK_SHARE);
			break;
		case WeiboShareUtil.SHARE_TO_TWITTER:
			wayValue = UmengUtils.WeiboTypeValue.TWITTER;
			mWeiboShare = WeiboShareFactory
					.getInstance(WeiboShareFactory.TWITTER_SHARE);
			break;
		case WeiboShareUtil.SHARE_TO_SINA:
			shareChannelStr = "weibo";
			wayValue = UmengUtils.WeiboTypeValue.SINA_WEIBO;
			mWeiboShare = WeiboShareFactory
					.getInstance(WeiboShareFactory.SINA_SHARE);
			break;
		case WeiboShareUtil.SHARE_TO_TENCENT:
			shareChannelStr = "qq";
			wayValue = UmengUtils.WeiboTypeValue.QZONE;
			mWeiboShare = WeiboShareFactory
					.getInstance(WeiboShareFactory.TENCENT_SHARE);
			break;
		case WeiboShareUtil.SHARE_TO_WEIXIN:
			shareChannelStr = "weixin";
			wayValue = UmengUtils.WeiboTypeValue.WEIXIN;
			mWeiboShare = WeiboShareFactory
					.getInstance(WeiboShareFactory.WEIXIN_SHARE);
			isShareWeixin = true;
			break;
		case WeiboShareUtil.SHARE_TO_WEIXIN_2:
			shareChannelStr = "weixin";
			wayValue = UmengUtils.WeiboTypeValue.WEIXIN;
			mWeiboShare = WeiboShareFactory
					.getInstance(WeiboShareFactory.WEIXIN_SHARE);
			isShareWeixin = true;
			break;
		case WeiboShareUtil.SHARE_TO_WEIXIN_FRIEND:
			shareChannelStr = "weixin";
			wayValue = UmengUtils.WeiboTypeValue.WEIXIN;
			mWeiboShare = WeiboShareFactory
					.getInstance(WeiboShareFactory.WEIXIN_SHARE);
			isShareWeixin = true;
			break;
		default:
			wayValue = "null";
			mWeiboShare = null;
			break;
		}

		if (mWeiboShare == null) {
			return;
		}
		shareChannel = shareTo;

		UmengUtils.markEvent(this, UmengUtils.Event.WEIBO_SHARE, new String[] {
				UmengUtils.ArgName.WAY, UmengUtils.ArgName.IS_FOLLOW },
				new String[] {
						wayValue,
						mIsFollow ? UmengUtils.BooleanTypeValue.TRUE
								: UmengUtils.BooleanTypeValue.FALSE });

		// String content = WeiboShareUtil.getShareTextWithParam(shareTo,
		// param);
		String content = "";
		if (!TextUtils.isEmpty(param.shareContent)) {
			content = param.shareContent;
		}
		// if (param.mShareType == ShareContentParam.SHARE_TYPE_SOUND) {
		// if ((App.myVcard.getVoiceintro() != null)) {
		// content += WeiboShareUtil.getMyHomePageUrl();
		// }
		// }

		// 微信分享
		if (isShareWeixin) {
			param.isShareUrl = true;
			if (param.mShareType == ShareContentParam.SHARE_TYPE_HOME_PAGE
					|| param.mShareType == ShareContentParam.SHARE_TYPE_USE) {
				// if (!TextUtils.isEmpty(param.bareJid)) {
				// url = WeiboShareUtil.getUserHomePageUrl(param.bareJid);
				// } else {
				// url = "http://www.imeach.com";
				// }
				url = getString(R.string.TxtAppUrl);

			}
		}

		isFollowDone = false;
		isShareDone = false;
		isFollowSuccess = false;
		isShareSuccess = false;
		isShowTip = true;

		isDoingShare = true;

		isFollowDone = !mIsFollow;
		isShareDone = false;
		if (isShareWeixin) {
			isFollowDone = true;
			if (shareTo == WeiboShareUtil.SHARE_TO_WEIXIN_2) {
				new WeiXinShare().getWeixinInstance(baseShareCallBack)
						.sharePersonaHomeWeiXin(content, url,
								WeiXin.THUMB_SIZE, WeiXin.THUMB_SIZE);
			} else {
				new WeiXinShare().getWeixinInstance(baseShareCallBack)
						.sharePersonaHomeWeiXinFri(content, url,
								WeiXin.THUMB_SIZE, WeiXin.THUMB_SIZE);
			}
			return;
			// (WeiXinShare)mWeiboShare.getWeixinInstance.sharePersonaHomeWeiXin(content,
			// url,
			// WeiXin.THUMB_SIZE, WeiXin.THUMB_SIZE);
		}
		if (param.isShareUrl) {
			mWeiboShare.shareWithImageUrl(this, content, url, mIsFollow,
					baseShareCallBack);
		} else {
			mWeiboShare.share(this, content, url, mIsFollow, baseShareCallBack);
		}
	}

	private Callback baseShareCallBack = new Callback() {

		@Override
		public void onSuccess(int action) {
			switch (action) {
			case IWeiboShare.ACTION_FOLLOW:
				isFollowDone = true;
				isFollowSuccess = true;
				break;
			case IWeiboShare.ACTION_SHARE:
				isShareDone = true;
				isShareSuccess = true;
				break;
			}
			if (mMissionId != null && mMissionId.equals("forpointsshare")) {
				runOnUiThread(new Runnable() {
					public void run() {
						isDoingShare = false;
						MyToastUtil.getInstance().showToastOnCenter(
								getString(R.string.TxtSnsSharesuccess));
						onShareSuccess();
					}
				});
				return;
			}
			runOnUiThread(new Runnable() {
				public void run() {
					if (mMissionId != null) {
						baseTaskCheckShowTip();
					} else {
						baseCheckShowTip();
					}
				}
			});
		}

		@Override
		public void onFailed(int action) {

			switch (action) {
			case IWeiboShare.ACTION_FOLLOW:
				isFollowDone = true;
				isFollowSuccess = false;
				break;
			case IWeiboShare.ACTION_SHARE:
				isShareDone = true;
				isShareSuccess = false;
				break;
			case IWeiboShare.ACTION_AUTHORIZE:
				isFollowDone = true;
				isShareDone = true;
				isFollowSuccess = false;
				isShareSuccess = false;
				break;
			}
			if (mMissionId != null && mMissionId.equals("forpointsshare")) {
				runOnUiThread(new Runnable() {
					public void run() {
						isDoingShare = false;
						MyToastUtil.getInstance().showToastOnCenter(
								getString(R.string.TxtSnsShareFail));
						onShareFail();
					}
				});
				return;
			}
			runOnUiThread(new Runnable() {
				public void run() {
					if (mMissionId != null) {
						baseTaskCheckShowTip();
					} else {
						baseCheckShowTip();
					}
				}
			});
		}

		@Override
		public void onStartShare() {
			// TODO Auto-generated method stub
			onShareStart();
		}

		@Override
		public void onGetFriends(ArrayList<User> list) {
			// TODO Auto-generated method stub

		}
	};

	private synchronized void baseCheckShowTip() {
		if (!isShowTip)
			return;

		if (isShareDone && isFollowDone) {
			isShowTip = false;

			ALLog.d("分享完成鸟。");
			isDoingShare = false;
			// 要金币
			if (mNeedGetGold) {
				ALLog.d("向服务器要金币");
				int delay = 0;

				if (isFollowSuccess) {
					ALLog.d("发请求获取关注金币");
					android.os.Message msg = new android.os.Message();
					msg.arg1 = GET_FOLLOW_GOLD;
					msg.arg2 = mWeiboType;
					baseGetGoldHandler.sendMessage(msg);
					delay += 2000;
				} else {
					ALLog.d("关注失败鸟，不给你金币。");
					MyToastUtil.getInstance().showToastOnCenter(
							getString(R.string.TxtSnsAddFriendFail));
				}

				if (isShareSuccess) {
					ALLog.d("延迟" + delay + "秒发请求获取分享金币");
					android.os.Message msg = new android.os.Message();
					msg.arg1 = GET_SHARE_GOLD;
					msg.arg2 = mWeiboType;
					baseGetGoldHandler.sendMessageDelayed(msg, delay);
				} else {
					ALLog.d("分享失败鸟，不给你金币。");
					MyToastUtil.getInstance().showToastOnCenter(
							getString(R.string.TxtSnsShareFail));
				}

				return;
			}

			// 不要金币
			if (isShareSuccess && isFollowSuccess) {
				ALLog.d("分享关注成功鸟。");
				MyToastUtil.getInstance().showToastOnCenter(
						getString(R.string.TxtSnsSharesuccess));

				return;
			}

			if (mIsFollow) {
				if (isFollowSuccess) {
					ALLog.d("关注成功鸟。");
					MyToastUtil.getInstance().showToastOnCenter(
							getString(R.string.TxtSnsAddFriendSuccess));
				} else {
					ALLog.d("关注失败鸟。");
					MyToastUtil.getInstance().showToastOnCenter(
							getString(R.string.TxtSnsAddFriendFail));
				}
			}

			if (isShareSuccess) {
				ALLog.d("分享成功鸟。");
				MyToastUtil.getInstance().showToastOnCenter(
						getString(R.string.TxtSnsSharesuccess));
			} else {
				ALLog.d("分享失败鸟。");
				MyToastUtil.getInstance().showToastOnCenter(
						getString(R.string.TxtSnsShareFail));
			}
		}
	}

	private static final int GET_FOLLOW_GOLD = 1;
	private static final int GET_SHARE_GOLD = 2;
	private Handler baseGetGoldHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {

			int goldType = msg.arg1;
			int weiboType = msg.arg2;

			String getGoldType = "";

			if (goldType == GET_FOLLOW_GOLD) {
				switch (weiboType) {
				case WeiboShareUtil.SHARE_TO_FACEBOOK:
					ALLog.d("facebook没有关注金币，88！");
					// getGoldType =
					// GoldAwardHttpRqWrap.AWARD_FACEBOOK_FRIEND;
					break;
				case WeiboShareUtil.SHARE_TO_TWITTER:
					ALLog.d("我要twitter关注的金币！");
					// getGoldType =
					// MissionAwardHttpRqWrap.AWARD_TWITTER_FRIEND;
					break;
				case WeiboShareUtil.SHARE_TO_SINA:
					ALLog.d("我要sina关注的金币！");
					// getGoldType = MissionAwardHttpRqWrap.AWARD_SINA_FRIEND;
					break;
				case WeiboShareUtil.SHARE_TO_TENCENT:
					ALLog.d("QQ没有关注金币，88！");
					// getGoldType =
					// GoldAwardHttpRqWrap.AWARD_TENCENT_FRIEND;
					break;
				}

			} else if (goldType == GET_SHARE_GOLD) {
				switch (weiboType) {
				case WeiboShareUtil.SHARE_TO_FACEBOOK:
					ALLog.d("我要facebook分享的金币！");
					// getGoldType =
					// MissionAwardHttpRqWrap.AWARD_FACEBOOK_SHARE;
					break;
				case WeiboShareUtil.SHARE_TO_TWITTER:
					ALLog.d("我要twitter分享的金币！");
					// getGoldType = MissionAwardHttpRqWrap.AWARD_TWITTER_SHARE;
					break;
				case WeiboShareUtil.SHARE_TO_SINA:
					ALLog.d("我要sina分享的金币！");
					// getGoldType = MissionAwardHttpRqWrap.AWARD_SINA_SHARE;
					break;
				case WeiboShareUtil.SHARE_TO_TENCENT:
					ALLog.d("我要qq分享的金币！");
					// getGoldType = MissionAwardHttpRqWrap.AWARD_QQ_ZONE_SHARE;
					break;
				}
			}

			if (!TextUtils.isEmpty(getGoldType)) {
				// Intent intent = new Intent(
				// Events.ACTION_NOTIFY_SERVER_SHARE_RESULT);
				// intent.putExtra("type", getGoldType);
				// sendBroadcast(intent);
			}

		}
	};

	/**
	 * 分享任务，成功发送完成任务请求
	 */
	private synchronized void baseTaskCheckShowTip() {
		if (!isShowTip)
			return;

		if (isShareDone && isFollowDone) {
			isShowTip = false;

			isDoingShare = false;
			if (isShareSuccess) {
				ALLog.d("分享成功鸟。");
				// MyToastUtil.getInstance().showToastOnCenter(
				// getString(R.string.TxtSnsSharesuccess));
				Toast.makeText(getApplicationContext(),
						getString(R.string.TxtSnsSharesuccess),
						Toast.LENGTH_SHORT).show();
				baseTaskCompleteHandler.sendEmptyMessage(0);

			} else {
				ALLog.d("分享失败鸟，不给你金币。");
				MyToastUtil.getInstance().showToastOnCenter(
						getString(R.string.TxtSnsShareFail));
			}
		}
	}

	private Handler baseTaskCompleteHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {

			ALLog.e("通知服务器任务完成");

			ALMissionManager.getDefaultMissionManager().onShareTaskFinish(
					shareChannelStr,
					mMissionId,
					ALLocalEnv.getLocalEnv().getVersionConfig().getServerInfo()
							.getTaskJava());
			// Intent intent = new Intent(
			// Events.ACTION_REQUEST_SYSTEM_RECEIVE_AWARDS);
			// /**
			// * 1.finishtask 表示完成任务 2.getaward 表示领奖
			// */
			// intent.putExtra("type", MissionAwardHttpRqWrap.TYPE_FINISH_TASK);
			// intent.putExtra("id", mMissionId);
			// sendBroadcast(intent);
			//
			// String channel = getShareChannel(shareChannel);
			//
			// HttpDataAsynHelper.newFinishTaskRequest(
			// App.myAccount.getUsername(), App.myAccount.getToken(),
			// mMissionId, channel, finishTaskCallback);

		}
	};

	// private HttpDataAsynHelper.Callback finishTaskCallback = new
	// HttpDataAsynHelper.Callback() {
	//
	// @Override
	// public void onSuccess(HttpResultWrap data) {
	// // TODO Auto-generated method stub
	// onShareSuccess();
	// }
	//
	// @Override
	// public void onSuccess(Bundle data) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onError(Exception e) {
	// // TODO Auto-generated method stub
	// ALLog.e( "获取奖励出错");
	// }
	// };

	private String getShareChannel(int shareTo) {
		String shareChannel = null;
		switch (shareTo) {
		case WeiboShareUtil.SHARE_TO_SINA:
			shareChannel = "WEIBO";
			break;
		case WeiboShareUtil.SHARE_TO_TENCENT:
			shareChannel = "QQ";
			break;
		case WeiboShareUtil.SHARE_TO_WEIXIN:
			shareChannel = "WEIXIN";
			break;
		}

		return shareChannel;
	}

	protected void onShareSuccess() {

	}

	protected void onShareFail() {

	}

	protected void onShareStart() {

	}

	/**************************************************************************** 下面是处理网络连接建立和丢失的回调 ******************************************************************************************************/

	@Override
	public void onDataConnectionEstablished(ALConnectionType type) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDataConnectionLost() {
		// TODO Auto-generated method stub

	}

	/********************************************************* 以下抽象函数为xmpp 事件回调，各界面根据相关需求重写相关函数 ***************************************************************************/

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.module.xmpp.ALXmppConnectionEventCallback#onALEvent(com.
	 * alstudio.pojo.ALLocalData)
	 */
	@Override
	public void onALEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		// 处理XMPP事件
		ALLog.d(activityName + " 收到XMPP事件 " + data.getType());
		dispatchXmppEvent(data);
	}

	/**
	 * 分发xmpp事件
	 * 
	 * @param data
	 */
	private void dispatchXmppEvent(ALXmppEvent data) {
		switch (data.getType()) {
		case XMPP_CLOSE_ACTIVITY_EVENT:
			// 关闭界面
			finish();
			ALLog.d("收到关闭界面消息");
			break;
		case XMPP_CONNECTION_STATE_CHANGED_EVENT:
			// xmpp连接状态改变
			handleConnectStateChangedEvent(data.getNewConnectionState(),
					data.getLastConnectionState());
			break;
		case XMPP_CONNECTION_ESTABLISHED_EVENT:
			// 登陆成功
			// loginedUpdataDataBase(data);
			handleLoginedEvent(data);
			break;
		case XMPP_CONNECTION_LOST_EVENT:
			// 连接断开
			// if (data.getErrorMessage().contains("conflict")) {
			// // 被踢下线
			// handleOnConflictEvent();
			// } else {
			// handleConnectionLostEvent(data.getErrorMessage());
			// }
			handleConnectionLostEvent(data.getErrorMessage());
			break;
		case XMPP_CONFILICT_LOGIN_EVENT:
			handleOnConflictEvent();
			break;
		case XMPP_AUTH_FAILED_EVENT:
			// 验证失败
			handleAuthFailedEvent(data.getErrorMessage());
			break;
		case XMPP_LOGOUT_SUCCESS_EVENT:
			// 注销成功
			handleLogoutEvent();
			break;
		case XMPP_IQ_PACKAGE_RECEIVE_EVENT:
			break;
		case XMPP_MESSAGE_PACKAGE_RECEIVE_EVENT:
			// 收到新Message消息
			switch (data.getMessage().getType()) {
			case ALMessage.NEW_INCOMMING_CALL:
				handleNewIncommingCallEvent(data.getMessage());
				break;
			case ALMessage.USER_ACCEPT_CALL:
				handleUserAcceptCallEvent(data.getMessage());
				break;
			case ALMessage.USER_HANDUP_CALL:
				handleUserHandupEvent(data.getMessage());
				break;
			case ALMessage.USER_REJECT_CALL:
				handleUserRejectCallEvent(data.getMessage());
				break;
			case ALMessage.USER_VOIP_ADDR_SET:
				handleUserVoipAddrSetEvent(data.getMessage());
				break;
			default:
				handleOnNewMessageArrivedEvent(data.getMessage());
				break;
			}
			break;
		case XMPP_PRESENCE_PACKAGE_RECEIVE_EVENT:
			break;
		case XMPP_MESSAGE_BACK_RECEIVE_EVENT:
			// 消息回执
			handleOnMessageReceiptEvent();
			break;
		/*********************** 注册登陆 ***********************************/
		case XMPP_CHECK_EMAIL_EVENT:
			handleCheckEmailEvent(data.getBoolean());
			break;
		case XMPP_CHECK_THIRD_PART_REGISTER_EVENT:
			handleCheckThirdPartLoginStateEvent(data);
			break;
		case XMPP_REGISTER_EVENT:
			handleRegisterEvent(data);
			break;

		/*********************** voip ***********************************/
		case XMPP_ACCEPT_INCOMMING_CALL_RESULT:
			handleAcceptCallEvent(data);
			break;
		case XMPP_CANCEL_CALL_RESULT:
			handleCancelCallEvent(data);
			break;
		case XMPP_HANDUP_CALL_RESULT:
			handleHandupCallEvent(data);
			break;
		case XMPP_MAKE_CALL_RESULT:
			handleMakeCallEvent(data);
			break;
		case XMPP_NEW_INCOMMING_CALL:
			break;
		case XMPP_REJECT_INCOMMING_CALL_RESULT:
			handleRejectCallEvent(data);
			break;
		case XMPP_ENTER_BAO_MI_HUA_RESULT:
			// 进入爆米花
			handleEnterBaoMiHuaEvent(data);
			break;
		case XMPP_EXIT_BAO_MI_HUA_RESULT:
			// 退出爆米花
			handleExitBaoMiHuaEvent(data);
			break;
		case XMPP_ENTER_XIEHOU_RESULT:
			// 进入邂逅
			handleEnterXieHouEvent(data);
			break;
		case XMPP_SET_VOIP_CALL_PRICE_RESULST:
			handleSetVoipCallPriceEvent(data);
			break;
		case XMPP_CHECK_VOIP_CALL_PRICE_LIST_RESULT:
			handleCheckVoipCallPriceListEvent(data);
			break;
		case XMPP_CHECK_CALL_HISTORY_DETAIL_RESULT:
			handleCheckCallHistoryDetailEvent(data);
			break;
		case XMPP_DELETE_CALL_HISTORY_DETAIL_RESULT:
			handleDeleteCallHistoryDetailEvent(data);
			break;
		case XMPP_CHECK_VOIP_RECORD_RESULT:
			handleCheckVoipRecordResult(data);
			break;
		/*********************** 发现搜索 *************************************/
		case XMPP_DISCOVERY_RESULT:
			handleDiscoveryResult(data);
			break;
		case XMPP_GLOBAL_SEARCH_RESULT:
			handleGlobalSearchResult(data);
			break;
		case XMPP_GET_RANK_RESULT:
			handleRankResult(data);
			break;
		case XMPP_GET_RANKING_RANK_RESULT:
			handleRankingRankResult(data);
			break;
		/******************************** 用戶相關操作 ****************************************/
		case XMPP_GET_FRIENDS_LIST_RESULT:
			handleFriendsListResult(data);
			break;
		case XMPP_CHECK_FAVORITES_EACH_OTHER_RESULT:
			// 相互关注
			handleGetFavoritesEachOtherResult(data);
			break;
		case XMPP_GET_DELET_FRIENDS_OR_FANS_RESULT:
			// 删除好友或者粉丝
			handleDeleteFriendsOrFans(data);
			break;
		case XMPP_GET_USER_PROFILE_RESULT:
			// 获取用户资料
			handleGetUserProfileEvent(data);
			break;
		case XMPP_GET_MODIFY_USER_PROFILE_RESULT:
			// 修改个人资料
			handleModifyUserProfileEvent(data);
			break;
		case XMPP_ADD_USER_NORMAL_OR_SPECIAL_FAVORITES_RESULT:
			// 添加关注或者特别关注
			handleAddUserFavoritesEvent(data);
			break;
		case XMPP_SET_USER_NOTENAME_RESULT:
			// 添加备注名
			handleSetUserNoteNameEvent(data);
			break;
		case XMPP_ADD_USER_TO_BLACK_LIST_RESULT:
			// 加入黑名单
			handleAddUserToBlackListEvent(data);
			break;
		case XMPP_DELETE_USER_TO_BLACK_LIST_RESULT:
			handleDeleteUserFromBlackListEvent(data);
			break;
		case XMPP_CHECK_BLACK_LIST_RESULT:
			handleBlackListOptEvent();
			break;
		/******************************** 賬號設置 *************************************************/
		case XMPP_CHANGE_PASSWORD_RESULT:
			// 更改密码
			handleChangePasswordEvent(data);
			break;
		case XMPP_FEEDBACK_RESULT:
			// 反馈结果
			handleFeedBackEvent(data);
			break;
		case XMPP_COMMIT_USER_OPTION_RESULT:
			// 提交用户配置
			handleCommitUserOptionEvent(data);
			break;
		case XMPP_GET_USER_OPTION_RESULT:
			// 得到用户配置
			handleGetUserOptionEvent(data);
			break;
		case XMPP_GET_START_VAUTH_RESULT:
			handleGetStartVauthResult(data);
			break;
		case XMPP_GET_USER_VAUTH_STATE_RESULT:
			handleGetVauthStateResult(data);
			break;
		case XMPP_BIND_EMAIL_RESULT:
			// 绑定邮箱
			handleBindEmailResult(data);
			break;
		case XMPP_BIND_EMAIL_AGAIN_RESULT:
			// 再次绑定邮箱
			handleBindEmailAaginResult(data);
			break;

		/*********************************** 經濟系統 **********************************************/
		case XMPP_DELETE_USER_MONEY_OR_POINTS_HISTORY_RESULT:
			// 清空积分或者账单记录
			handleDeleteUserMoneyOrPointsHistoryEvent(data);
			break;
		case XMPP_GET_RECHARGE_PRICE_RESULT:
			// 充值价格表
			handleGetRechargePriceEvent(data);
			break;
		case XMPP_GET_USER_MONEY_OR_POINTS_HISTORY_RESULT:
			// 得到账单或者积分记录
			handleGetUserMoneyOrPointsHistoryEvent(data);
			break;
		case XMPP_GET_USER_POINTS_RESULT:
			// 得到积分
			handleGetUserPointsEvent(data);
			break;
		/************************************** 道具系统 *****************************************************/
		// 獲取道具商城列表
		case XMPP_GET_PROPS_LIST_RESULT:
			handleGetPropsListEvent(data);
			break;
		// 獲取道具價格
		case XMPP_GET_PROPS_PRICE_RESULT:
			handleGetPropsPriceEvent(data);
			break;
		// 獲取我的道具
		case XMPP_GET_USER_PROPS_RESULT:
			handleGetUserPropsListEvent(data);
			break;
		// 獲取道具購買明細
		case XMPP_GET_USER_PROPS_HISTORY_RESULT:
			handleGetUserPropsHistoryEvent(data);
			break;
		// 清除道具購買明細
		case XMPP_DELETE_USER_PROPS_HISTORY_RESULT:
			handleGetDeleteUserPropsHistoryEvent(data);
			break;
		// 激活道具结果
		case XMPP_ACTIVIE_PROPS_RESULT:
			handleActivePropsEvent(data);
			break;
		/************************ 系统消息 聊天消息处理 ************************************/
		case XMPP_RECEIVE_NEW_CALL_IMAGE_MESSAGE_EVENT:
			handleNewCallImageMessageEvent(data.getMessage());
			break;
		case XMPP_RECEIVE_NEW_SYSTEM_MESSAGE_EVENT:
			handleNewSystemMessageEvent(data.getMessage());
			break;
		case XMPP_RECEIVE_NEW_NOTE_MESSAGE_EVENT:
			handleNewNoteMessageEvent(data.getMessage());
			break;
		/************************ 任务处理 ************************************/
		case XMPP_MISSION_COMPLETED_EVENT:
			// 任务完成
			handleMissionCompletedEvent();
			break;
		case XMPP_NEW_MISSION_ALERT_EVENT:
			handleNewMissionAlertEvent(data);
			// 新任务通知
			break;
		default:
			break;
		}
	}

	public void handleConnectStateChangedEvent(ALXmppConnectionState newState,
			ALXmppConnectionState lastState) {
	}

	/**
	 * 登录成功后,此回调将被执行
	 * 
	 * @author alonso lee
	 */
	public void handleLoginedEvent(ALXmppEvent data) {
		third_part_uid = "";
		third_part_token = "";
		third_part_token_secret = ""; // twitter需要
		third_part_nickname = "";
		third_part_gender = "";
		third_part_birthday = null;
		third_part_avatar_path = "";
		ALLog.d("准备保存");
		// loginedUpdataDataBase(data);
	}

	/**
	 * 当接收到登出成功后，此回调将被执行
	 * 
	 * @author alonso lee
	 */
	public void handleLogoutEvent() {
	}

	protected void logOutUpdataDataBase() {

		new Thread() {
			public void run() {

				ALLocalEnv.getLocalEnv().getMyAccount().setLogoff(true);
				ALLocalEnv.getLocalEnv().getMyAccount().setPassWord("");

				ALLocalEnv.getLocalEnv().getDatabase()
						.saveMyAccount(ALLocalEnv.getLocalEnv().getMyAccount());
				// 注销后将账号密码清除

				ALLocalEnv.getLocalEnv().getDatabase().saveSystemSetting(false);

			};
		}.start();

	}

	/**
	 * 当连接丢失时，此回调将被执行
	 * 
	 * @author alonso lee
	 */
	public void handleConnectionLostEvent(String errorMessage) {
	}

	/**
	 * 当账号验证失败时，此回调将被执行
	 * 
	 * @author alonso lee
	 */
	public void handleAuthFailedEvent(String errorMessage) {
	}

	/**
	 * 当账号冲突被踢下线时，此回调将被执行
	 * 
	 * @author alonso lee
	 */
	public void handleOnConflictEvent() {
		finish();
	}

	/**
	 * 当收到Message消息时，此回调将被执行
	 * 
	 * @author alonso lee
	 */
	public void handleOnNewMessageArrivedEvent(ALMessage msg) {
	}

	/**
	 * 当收到Message消息回执时，此回调将被执行
	 * 
	 * @author alonso lee
	 */
	public void handleOnMessageReceiptEvent() {
	}

	/************************************************* voip ***************************************************************/
	/**
	 * 有新来电
	 * 
	 * @param msg
	 */
	public void handleNewIncommingCallEvent(ALMessage msg) {
		// ALLog.d("有来电，开启通话界面");
		// Intent i = new Intent(this, CallActivity.class);
		// i.putExtra("msg", msg);
		// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
		// | Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
		// // i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
		// // Intent.FLAG_ACTIVITY_NEW_TASK);
		// startActivity(i);
		// // ALMediaManager.getInstance(this).playRing(R.raw.msg, true);
		// ALVoipMediaManager.getDefaultMediaManager(
		// ALLocalEnv.getLocalEnv().getApplicationContext())
		// .playIncommingCallRingtone();

	}

	/**
	 * 电话已接通
	 * 
	 * @param msg
	 */
	public void handleUserAcceptCallEvent(ALMessage msg) {

	}

	/**
	 * 对方拒绝来电
	 * 
	 * @param msg
	 */
	public void handleUserRejectCallEvent(ALMessage msg) {

	}

	/**
	 * 对方挂断电话
	 * 
	 * @param msg
	 */
	public void handleUserHandupEvent(ALMessage msg) {

	}

	/**
	 * 拨打电话成功与否
	 * 
	 * @param msg
	 */
	public void handleMakeCallEvent(ALXmppEvent data) {
	}

	/**
	 * 取消拨打电话事件
	 * 
	 * @param data
	 */
	public void handleCancelCallEvent(ALXmppEvent data) {

	}

	/**
	 * 接听电话事件
	 * 
	 * @param data
	 */
	public void handleAcceptCallEvent(ALXmppEvent data) {

	}

	/**
	 * 挂断电话事件
	 * 
	 * @param data
	 */
	public void handleHandupCallEvent(ALXmppEvent data) {

	}

	/**
	 * 拒绝来电事件
	 * 
	 * @param data
	 */
	public void handleRejectCallEvent(ALXmppEvent data) {

	}

	/**
	 * 上传本地网络环境到voip模块事件
	 * 
	 * @param msg
	 */
	public void handleUserVoipAddrSetEvent(ALMessage msg) {

	}

	/**
	 * 处理进入爆米花
	 * 
	 * @param data
	 */
	public void handleEnterBaoMiHuaEvent(ALXmppEvent data) {

	}

	/**
	 * 退出爆米花
	 * 
	 * @param data
	 */
	public void handleExitBaoMiHuaEvent(ALXmppEvent data) {

	}

	/**
	 * 进入邂逅
	 * 
	 * @param data
	 */
	public void handleEnterXieHouEvent(ALXmppEvent data) {

	}

	/**
	 * 设置voip价格结果
	 * 
	 * @param data
	 */
	public void handleSetVoipCallPriceEvent(ALXmppEvent data) {

	}

	/**
	 * 获取voip价格列表
	 * 
	 * @param data
	 */
	public void handleCheckVoipCallPriceListEvent(ALXmppEvent data) {

	}

	/**
	 * 获取通话详情
	 * 
	 * @param data
	 */
	public void handleCheckCallHistoryDetailEvent(ALXmppEvent data) {

	}

	/**
	 * 删除通话详情
	 * 
	 * @param data
	 */
	public void handleDeleteCallHistoryDetailEvent(ALXmppEvent data) {

	}

	private final int CHECK_VOIP_RECORD_STRANGER = 0;
	private final int CHECK_VOIP_RECORD_FRIENDS = 1;
	private final int CHECK_VOIP_RECORD_BAOMIHUA = 2;

	private void handleCheckVoipRecordResult(ALXmppEvent data) {
		switch (data.getIntData()) {
		case CHECK_VOIP_RECORD_STRANGER:
			handleGetStrangerVoipRecord(data);
			break;
		case CHECK_VOIP_RECORD_FRIENDS:
			handleGetFriendsVoipRecord(data);
			break;
		case CHECK_VOIP_RECORD_BAOMIHUA:
			handleGetBaoMiHuaVoipRecord(data);
			break;
		}
	}

	/**
	 * 得到陌生人通话记录
	 * 
	 * @param data
	 */
	public void handleGetStrangerVoipRecord(ALXmppEvent data) {

	}

	/**
	 * 得到好友通话记录
	 * 
	 * @param data
	 */
	public void handleGetFriendsVoipRecord(ALXmppEvent data) {

	}

	/**
	 * 得到爆米花通话记录
	 * 
	 * @param data
	 */
	public void handleGetBaoMiHuaVoipRecord(ALXmppEvent data) {

	}

	/******************************* 注册 *************************************/
	/**
	 * 检测email是否可用事件
	 * 
	 * @param isEmailAvailable
	 */
	public void handleCheckEmailEvent(boolean isEmailAvailable) {

	}

	/**
	 * 注册事件
	 * 
	 * @param data
	 */
	public void handleRegisterEvent(ALXmppEvent data) {

	}

	/**
	 * 检测第三方账号登陆事件
	 * 
	 * @param data
	 */
	public void handleCheckThirdPartLoginStateEvent(ALXmppEvent data) {

	}

	/******************************* 用户相关 *************************************/
	/**
	 * 处理发现事件
	 */
	public void handleDiscoveryResult(ALXmppEvent data) {
	}

	/**
	 * 处理全局搜索事件
	 */
	public void handleGlobalSearchResult(ALXmppEvent data) {
	}

	/**
	 * 处理获取用户资料
	 * 
	 * @param data
	 */
	public void handleGetUserProfileEvent(ALXmppEvent data) {
		// if (data.getResponseCode() == 0 && data.getData() != null) {
		// User user = (User) data.getData();
		// if (ALLocalEnv.getBareJid(user.getJid()).equals(
		// ALLocalEnv.getLocalEnv().getMyAccount().getUserName())) {
		// // 开始保存自己的资料
		// UserProfileManager.saveMyProfile(user);
		// ALLocalEnv.getLocalEnv().setMyProfile(user);
		// }
		//
		// }
	}

	/**
	 * 处理修改用户资料结果
	 * 
	 * @param data
	 */
	public void handleModifyUserProfileEvent(ALXmppEvent data) {
	}

	/**
	 * 排行榜事件
	 * 
	 * @param data
	 */
	public void handleRankResult(ALXmppEvent data) {

	}

	/**
	 * 排行榜排名事件
	 * 
	 * @param data
	 */
	public void handleRankingRankResult(ALXmppEvent data) {

	}

	/**
	 * 获取好友列表事件
	 * 
	 * @param data
	 */
	public void handleFriendsListResult(ALXmppEvent data) {

	}

	/**
	 * 获取相互关注
	 * 
	 * @param data
	 */
	public void handleGetFavoritesEachOtherResult(ALXmppEvent data) {

	}

	/**
	 * 处理删除好友或者粉丝
	 * 
	 * @param data
	 */
	public void handleDeleteFriendsOrFans(ALXmppEvent data) {

	}

	/**
	 * 处理普通关注或者特别关注
	 * 
	 * @param data
	 */
	public void handleAddUserFavoritesEvent(ALXmppEvent data) {
	}

	/**
	 * 处理备注名
	 * 
	 * @param data
	 */
	public void handleSetUserNoteNameEvent(ALXmppEvent data) {

	}

	/**
	 * 处理加入黑名单
	 * 
	 * @param data
	 */
	public void handleAddUserToBlackListEvent(ALXmppEvent data) {

	}

	/**
	 * 处理解除黑名单
	 * 
	 * @param data
	 */
	public void handleDeleteUserFromBlackListEvent(ALXmppEvent data) {

	}

	/**
	 * 黑名单操作
	 */
	public void handleBlackListOptEvent() {

	}

	/******************************** 賬號設置 *************************************************/
	/**
	 * 处理更改密码
	 * 
	 * @param data
	 */
	public void handleChangePasswordEvent(ALXmppEvent data) {

	}

	/**
	 * 处理反馈意见
	 * 
	 * @param data
	 */
	public void handleFeedBackEvent(ALXmppEvent data) {

	}

	/**
	 * 处理提交用户设置
	 * 
	 * @param data
	 */
	public void handleCommitUserOptionEvent(ALXmppEvent data) {
	}

	/**
	 * 处理获取用户设置
	 * 
	 * @param data
	 */
	public void handleGetUserOptionEvent(ALXmppEvent data) {

	}

	/**
	 * 处理请求V认证结果
	 * 
	 * @param data
	 */
	public void handleGetStartVauthResult(ALXmppEvent data) {

	}

	/**
	 * 处理获取V认证状态
	 * 
	 * @param data
	 */
	public void handleGetVauthStateResult(ALXmppEvent data) {

	}

	/**
	 * 绑定邮箱
	 * 
	 * @param data
	 */
	public void handleBindEmailResult(ALXmppEvent data) {

	}

	/**
	 * 再次发一封
	 * 
	 * @param data
	 */
	public void handleBindEmailAaginResult(ALXmppEvent data) {

	}

	/*********************************** 經濟系統 **********************************************/

	/**
	 * 清空积分或者账单记录
	 * 
	 * @param data
	 */
	public void handleDeleteUserMoneyOrPointsHistoryEvent(ALXmppEvent data) {

	}

	/**
	 * 充值价格表
	 * 
	 * @param data
	 */
	public void handleGetRechargePriceEvent(ALXmppEvent data) {

	}

	/**
	 * 得到账单或者积分记录
	 * 
	 * @param event
	 */
	public void handleGetUserMoneyOrPointsHistoryEvent(ALXmppEvent data) {

	}

	/**
	 * 得到积分
	 * 
	 * @param data
	 */
	public void handleGetUserPointsEvent(ALXmppEvent data) {

	}

	/************************************** 道具系统 *****************************************************/
	/**
	 * 得到商城列表
	 * 
	 * @param data
	 */
	public void handleGetPropsListEvent(ALXmppEvent data) {

	}

	/**
	 * 獲取道具價格
	 * 
	 * @param data
	 */
	public void handleGetPropsPriceEvent(ALXmppEvent data) {

	}

	/**
	 * 獲取我的道具
	 * 
	 * @param data
	 */
	public void handleGetUserPropsListEvent(ALXmppEvent data) {

	}

	/**
	 * 獲取道具購買明細
	 * 
	 * @param data
	 */
	public void handleGetUserPropsHistoryEvent(ALXmppEvent data) {

	}

	/**
	 * 清除道具購買明細
	 * 
	 * @param data
	 */
	public void handleGetDeleteUserPropsHistoryEvent(ALXmppEvent data) {

	}

	/**
	 * 激活道具结果
	 * 
	 * @param data
	 */
	public void handleActivePropsEvent(ALXmppEvent data) {

	}

	/**
	 * 收到新的通话中图片消息
	 * 
	 * @param msg
	 */
	public void handleNewCallImageMessageEvent(ALMessage msg) {

	}

	/**
	 * 收到新的系统通知
	 * 
	 * @param msg
	 */
	public void handleNewSystemMessageEvent(ALMessage msg) {

	}

	/**
	 * 收到新的留言消息
	 * 
	 * @param msg
	 */
	public void handleNewNoteMessageEvent(ALMessage msg) {

	}

	/****************************************** 任务处理 ******************************************************/
	/**
	 * 全部任务已完成
	 */
	public void handleMissionCompletedEvent() {

	}

	/**
	 * 新任务
	 * 
	 * @param event
	 */
	public void handleNewMissionAlertEvent(ALXmppEvent event) {

	}

	/***************************************** voip 通话状态 ***************************************************/
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.core.voip.ALVoipCallUIEventCallback#onALEvent(com.alstudio
	 * .core.voip.ALVoipUIEvent)
	 */
	@Override
	public void onALEvent(ALVoipUIEvent data) {
		// TODO Auto-generated method stub
		String callId = (String) data.getData();
		switch (data.getType()) {
		case ALVOIP_UI_EVENT_ESTABLISHED_CALL:
			handleCallEstablisedEvent(callId);
			break;
		case ALVOIP_UI_EVENT_HANDUP_CALL:
			handleReloadCallInfoEvent(callId);
			break;
		case ALVOIP_UI_EVENT_INCOMMING_CALL:
			handleReloadCallInfoEvent(callId);
			break;
		case ALVOIP_UI_EVENT_INCOMMING_CALL_NOTICE:
			// 来电提醒
			handleNewMissedCallEvent(callId);
			break;
		case ALVOIP_UI_EVENT_MISSED_CALL:
			// 新来电
			handleNewMissedCallEvent(callId);
			break;
		case ALVOIP_UI_EVENT_NONE:
			break;
		case ALVOIP_UI_EVENT_OUTGOING_CALL:
			handleReloadCallInfoEvent(callId);
			break;
		case ALVOIP_UI_EVENT_REJECT_CALL:
			handleReloadCallInfoEvent(callId);
			break;
		case ALVOIP_UI_EVENT_FORCE_REFRESH_CALL_HISTORY:
			handleForceRefreshCallHistoryEvent();
			break;
		default:
			break;
		}
	}

	public void handleForceRefreshCallHistoryEvent() {

	}

	public void handleNewMissedCallEvent(String callId) {

	}

	public void handleCallEstablisedEvent(String callId) {

	}

	public void handleReloadCallInfoEvent(String callId) {

	}

	/*************************************** 版本更新 ************************************************/

	public synchronized void showApkUpdateDialog(final ServerInfo info) {

		AlertDialogCreator dialog = null;

		if (info == null)
			return;
		if (info.isForceUpdate()) {
			ALLocalEnv.getLocalEnv().getVersionConfig().getServerInfo()
					.setForceUpdateState(true);
			// 强制更新
			dialog = AlertDialogCreator
					.createOneButtonNormalDialog(this, false);
			dialog.setCentralButtonName(getString(R.string.TxtUpdateNow));
			dialog.setCancelable(false);
			dialog.setCenterKeyListener(new AlDialogOnClickListener() {

				@Override
				public void onClick() {
					// TODO Auto-generated method stub
					// 断开当前连接
					ALUiXmppRequestCreator.postALUiXmppLogOutEvent();
					doNewVersion(info.getLatestVer(), info.getNewVersionUrl());
				}
			});
		} else {
			dialog = AlertDialogCreator
					.createTwoButtonNormalDialog(this, false);
			dialog.setLeftKeyListener(new AlDialogOnClickListener() {

				@Override
				public void onClick() {
					// TODO Auto-generated method stub
					doNewVersion(info.getLatestVer(), info.getNewVersionUrl());
				}
			});
		}

		dialog.setMessage(info.getWhatsNew());

		dialog.showDialog();

	}

	/**
	 * 显示无更新对话框
	 */
	public synchronized void showNoApkUpdateDialog() {
		AlertDialogCreator dialog = null;
		dialog = AlertDialogCreator.createOneButtonNormalDialog(this, false);
		dialog.setMessage(getString(R.string.TxtApkLatest));
		dialog.showDialog();
	}

	/**
	 * 处理用户更新版本事件
	 * 
	 * @author Alonso Lee
	 */
	protected synchronized void doNewVersion(String ver, String url) {
		if (ALUpdateApkManager.isDownloading()) {
			MyToastUtil.getInstance().showCenterToastOnCenter(
					R.string.TxtAlreadyDownloadingApk);
			return;
		}

		ALUpdateApkManager.startDownloadApk(ALLocalEnv.getLocalEnv(), url,
				VersionConfig.UPDATE_APK_PATH, ver + ".apk");

	}

	/**
	 * 检测是否有更新
	 */
	private void checkNewVersionAlert() {
		if (MainActivity.class.getSimpleName().equals(this.activityName)) {
			if (ALLocalEnv.getLocalEnv().isNewVersionArrive()) {
				showApkUpdateDialog(ALLocalEnv.getLocalEnv().getVersionConfig()
						.getServerInfo());
			}
		}
	}

}
